import {createRouter, createWebHistory} from 'vue-router';
import UserLogin from '../components/UserLogin.vue';
import UserRegister from '../components/UserRegister.vue';
import MainLayout from '../layouts/MainLayout.vue';

const routes = [
    {path: '/', redirect: '/index'},
    {path: '/login', component: UserLogin},
    {path: '/register', component: UserRegister},
    {path: '/index', component: MainLayout}
];

const router = createRouter({
    history: createWebHistory(),
    routes
});

router.beforeEach((to, _from, next) => {
    const isAuthenticated = !!localStorage.getItem('token'); // 判断是否已登录

    if (to.path !== '/login' && !isAuthenticated && to.path !== '/register') {
        next('/login');
    } else {
        next();
    }
});

export default router;
